package xyz.lisys.dozer.converter;

import com.github.dozermapper.core.CustomConverter;
import com.github.dozermapper.core.MappingException;

import java.lang.reflect.Method;

public class StringAndEnumDozerConverter implements CustomConverter {

    @Override
    public Object convert(Object destination, Object source, Class<?> destinationClass, Class<?> sourceClass) {
        if (source == null)
            return null;

        if (destinationClass != null) {
            if (sourceClass.isEnum()) {
                return getString(sourceClass, source);
            } else if (destinationClass.isEnum()) {
                return getEnum(destinationClass, source);
            } else {
                throw new MappingException(
                        "Converter " + getClass().getSimpleName() +
                                " was used incorrectly. Arguments were: " + Class.class.getName() + " and "
                                + source
                );
            }
        }

        return null;
    }

    private Object getEnum(Class<?> destinationClass, Object source) {
        if ("".equals(source)) {
            return null;
        }

        Method[] ms = destinationClass.getMethods();

        try {
            for (Method m : ms) {
                if (m.getName().equalsIgnoreCase("getEnumByCode")) {
                    return m.invoke(Class.class, source);
                }
            }

            Method m = destinationClass.getDeclaredMethod("valueOf", String.class);
            return m.invoke(Class.class, source);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private Object getString(Class<?> sourceClass, Object source) {
        try {
            Method m = sourceClass.getDeclaredMethod("getCode");
            return m.invoke(source);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
